package cn.whdream.juc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 
 * @author admin
 * 注意
 */
public class TestCopyOnWriteArrayList {
	public static void main(String[] args) {
		Copy c = new Copy();
		Copy1 c1 = new Copy1();
		for (int i = 0; i < 10; i++) {
			new Thread(c1).start();
		}
	}
	private static class Copy implements Runnable{
		private static List<String> list = Collections.synchronizedList(new ArrayList<String>());
		static {
			list.add("aa");
			list.add("bb");
			list.add("cc");
		}
		@Override
		public void run() {
			Iterator i =list.iterator();
			while (i.hasNext()) {
				System.out.println(i.next());
				list.add("ss");
			}	
		}
		
	}
	private static class Copy1 implements Runnable{
		//内存开销大，并发迭代可以适用
		private static List<String> list = new CopyOnWriteArrayList<>();
		static {
			list.add("aa");
			list.add("bb");
			list.add("cc");
		}
		@Override
		public void run() {
			Iterator i =list.iterator();
			while (i.hasNext()) {
				System.out.println(i.next());
				list.add("ss");
			}	
		}
		
	}
}
